<template>
  <div id="app" class="oval-header fixed-warp-body">
    <nav-bar
      class="trans-bar"
      :title="'订单号'+order_no"
      left-arrow
      @clickLeft="$goPageBack('order/list')"
    />

    <div v-if="data">
      <!-- BLOCK: 头部信息 -->
      <div class="mg-hor pd-top-xl mg-btm-xl c-white">
        <van-row>
          <van-col class="text-center font-xl font-xl-line" span="3" v-if="stateIcon">
            <van-icon class-prefix="ucai-icon" :name="stateIcon" />
          </van-col>
          <van-col span="15">
            <span class="mg-rgt-xl font-xl">{{data.state_name}}</span>
            <span class="font-xl-line" @click="showProgressSheet()">
              订单进度
              <van-icon class-prefix="ucai-icon" name="arrow_rgt" />
            </span>
          </van-col>
          <van-col class="font-xl-line text-right" span="6">
            <span @click="()=>this.isShowPriceSheet = true">
              <span class="font-sm">￥</span>
              <span class="font-lg">{{data.pay_amount}}</span>
              <van-icon class="font-lg" class-prefix="ucai-icon" name="zhushi" />
            </span>
          </van-col>
        </van-row>
        <van-row>
          <van-col span="21" offset="3">
            {{data.state_mark}}
          </van-col>
        </van-row>
      </div>

      <!-- BLOCK: 核销码（待使用） -->
      <voucher-panel
        v-if="state == 6"
        :order_no="order_no"
        :data="mainVoucher"
        :count="data.voucher_count"
        :date="data.avail_date_desc"
        :isCollapsed=false
      />

      <!-- BLOCK: 评价 -->
      <!-- <div class="panel-box mg-all">
    <div class="panel-head">
      待评价
      <div class="panel-head-tool">
        <van-button
          size="small"
          type="primary"
          round
          plain
        >去评价</van-button>
      </div>
    </div>
  </div> -->

      <!-- BLOCK: 产品信息 -->
      <prod-panel :data="data" :isCollapsed="isCollapsedProd" />

      <!-- BLOCK: 核销码（完成） -->
      <voucher-panel
        v-if="state != 6 && state != 0"
        :order_no="order_no"
        :data="mainVoucher"
        :count="data.voucher_count"
        :date="data.avail_date_desc"
        :isCollapsed=true
      />

      <!-- BLOCK: 发票 -->
      <!-- <div class="panel-box mg-all">
    <div class="panel-head">
      发票
      <div class="panel-head-tool">
        <van-button
          size="small"
          type="primary"
          round
          plain
        >申请发票</van-button>
      </div>
    </div>
    <ul class="panel-list">
    </ul>
  </div> -->

      <!-- BLOCK: 景区 -->
      <!-- <div class="panel-box mg-all">
    <div class="panel-head">
      花仙谷景区
      <div class="panel-head-tool">
        景区详情
        <van-icon class-prefix="ucai-icon" name="arrow_rgt" />
      </div>
    </div>
  </div> -->

      <!-- BLOCK: 客服 -->
      <div class="panel-box mg-all">
        <div class="panel-head">
          <van-row>
            <van-col span="7">客服咨询</van-col>
            <van-col span="17" class="c-main">
              <a :href="'tel:' + service_tel">{{service_tel}}</a>
            </van-col>
          </van-row>
        </div>
      </div>

      <!-- BLOCK: 提示&按钮 -->
      <div class="fixed-warp">
        <div v-if="state == 0" class="tips-warp">
          <div v-if="payment_timeout">
            剩余支付时间：
            <van-count-down :time="payment_timeout" format="mm 分 ss 秒" @finish="setPaymentTimeout(0)" />
          </div>
          <div v-else>
            支付超时
          </div>
        </div>
        <!-- 按钮组 -->
        <div class="btn-group">
          <van-button
            v-if="state == 1 || state == 2 || state == 3"
            size="small"
            type="default"
            plain
            hairline
            @click="onDelt"
          >删除</van-button>
          <van-button
            v-if="state != 0"
            size="small"
            type="default"
            plain
            hairline
            @click="onBooking"
          >再次预订</van-button>
          <van-button
            v-if="state == 6"
            size="small"
            type="default"
            plain
            hairline
            @click="doResendSms"
          >重发短信</van-button>
          <van-button
            v-if="state == 0 && payment_timeout"
            size="small"
            type="primary"
            plain
            :disabled="!payment_timeout"
            @click="onPayment"
          >继续支付</van-button>
        </div>
      </div>

      <!-- BLOCK: 弹窗-订单进度 -->
      <van-action-sheet v-model="isShowProgressSheet" title="订单进度">
        <div class="panel-block">
          <div class="panel-body">
            <van-steps direction="vertical" :active="progressList.length - 1" v-if="progressList && progressList.length > 0">
              <van-step v-for="(item, index) in progressList" :key="index">
                <h3>{{item.content}}</h3>
                <p>{{item.time}}</p>
              </van-step>
            </van-steps>
            <no-data v-else :text="progressErrMsg" />
          </div>
        </div>
      </van-action-sheet>

      <!-- BLOCK: 弹窗-费用明细 -->
      <van-action-sheet v-model="isShowPriceSheet" title="费用明细">
        <div class="panel-block">
          <div v-for="prod in data.product_list" :key="prod.product_id">
            <div class="panel-head">
              {{prod.product_name}}
            </div>
            <ul class="panel-list">
              <li v-for="item in prod.item_list" :key="item.id">
                <van-row>
                  <van-col class="title" span="16">{{item.sku_name}}</van-col>
                  <van-col class="desc text-right" span="8">￥{{item.sale_price}} × {{item.qty}}</van-col>
                </van-row>
              </li>
            </ul>
          </div>
          <div class="panel-foot font-lg text-right">
            订单总额：<span class="c-buy">￥{{data.pay_amount}}</span>
          </div>
        </div>
      </van-action-sheet>

    </div>
    <no-data v-else-if="errMsg" :text="errMsg" />
    <slogan />
  </div>
</template>

<script>
  import {
    Icon,
    Button,
    Row,
    Col,
    ActionSheet,
    Step,
    Steps,
    CountDown,
    Toast,
    Dialog,
  } from 'vant'
  import NavBar from "@cmpt/header/navbar"
  import CollapsePanel from "@cmpt/panel/collapse"
  import ProdPanel from './prod-panel'
  import VoucherPanel from './voucher-panel'
  import NoData from '@cmpt/no-data'
  import Slogan from '@cmpt/slogan'

  import {
    getOrderDetail,
    getOrderProgress,
    resendSms,
    deltOrder,
    getResubmitSecret,
  } from "@api/modules/order"
  import {
    getConfig
  } from '@api/modules/index'
  import {
    getErrInfo,
  } from "@api/http"
  import {
    getRole
  } from '@utils/role'

  import {
    ORDER_STATUS_LIST
  } from '@data/dic/order'

  export default {
    name: 'order-detail',
    components: {
      [Icon.name]: Icon,
      [Button.name]: Button,
      [Row.name]: Row,
      [Col.name]: Col,
      [ActionSheet.name]: ActionSheet,
      [Step.name]: Step,
      [Steps.name]: Steps,
      [CountDown.name]: CountDown,

      NavBar,
      CollapsePanel,
      ProdPanel,
      VoucherPanel,
      NoData,
      Slogan,
    },

    data() {
      return {
        order_no: this.$getUrlParam('order_no') || '',
        data: null,
        payment_timeout: 0, // 剩余支付时间
        customer_service: null, // 客服信息
        errMsg: '',
        // 订单进度
        progressList: null,
        progressErrMsg: '',
        isShowProgressSheet: false,
        // 费用明细
        isShowPriceSheet: false,
      }
    },

    computed: {
      firstProd: function () { // 第一个产品数据
        const data = this.data || {}
        const list = data.product_list || []
        return list[0] || {}
      },
      state: function () { // 订单状态(0:待支付 1:超时关闭 2:用户关闭 3:系统关闭 4:已支付 5:待确认 6:待完成 7:交易完成)
        const data = this.data || {}
        return data.state

      },
      stateIcon: function () {
        const status = this.state
        const obj = ORDER_STATUS_LIST.find((item) => {
          return item.key == status
        })
        return obj ? obj.icon : ''
      },
      isCollapsedProd: function () { // 是否折叠订单详细
        return this.state != 0 && this.state != 4 && this.state != 5
      },
      mainVoucher: function () { // 总核销码
        const data = this.data || {}
        return data.voucher || {}
      },
      service_tel: function () { // 客服电话【订单详情页的客户：从基础取;商品详情页的客服：从商品取，如果商品那取不到，就从基础那取；】
        if (!this.customer_service || !this.customer_service.phone)
          return '--'
        return this.customer_service.phone
      },
    },

    methods: {
      async getData() {
        Toast.loading({
          duration: 10000,
          forbidClick: true
        })
        getOrderDetail({
          order_no: this.order_no,
        }).then(res => {
          Toast.clear()
          this.data = res.data
          this.$set_page_title(`订单详情_${this.order_no}`)
          this.setPaymentTimeout(this.data.payment_timeout)
        }).catch(err => {
          this.data = null
          const {
            msg
          } = getErrInfo(err)
          this.errMsg = msg
        })
      },

      async getProgress() {
        Toast.loading({
          duration: 10000,
          forbidClick: true
        })
        getOrderProgress({
          order_no: this.order_no,
        }).then(res => {
          Toast.clear()
          this.progressList = res.data.progress || []
          this.isShowProgressSheet = true
        }).catch(err => {
          this.progressList = null
          const {
            msg
          } = getErrInfo(err)
          this.progressErrMsg = msg
          this.isShowProgressSheet = true
        })
      },

      async getService() {
        getConfig(['customer_service'])
          .then(res => {
            const data = res.data || {}
            this.customer_service = data.customer_service ? {
              ...data.customer_service
            } : {}
          })
      },

      setPaymentTimeout(seconds) {
        this.payment_timeout = (seconds || 0) * 1000
      },

      showProgressSheet() {
        if (this.progressList) {
          this.isShowProgressSheet = true
          return
        }
        this.getProgress()
      },

      onBooking() {
        const role = getRole()
        if (role !== '0') {
          this.$goPage('booking', {
            product_id: this.firstProd.product_id
          })
          return
        }
        // 游客请求加密传后跳转
        getResubmitSecret({
          order_no: this.data.order_no
        }).then(res => {
          const data = res.data
          this.$goPage('booking', {
            product_id: data.product_id,
            secret: data.secret
          })
        }).catch(err => {})
      },

      onPayment() {
        this.$goPage('payment', {
          type: 1,
          order_no: this.data.order_no
        })
      },

      doResendSms() {
        Dialog.confirm({
          message: `向手机 ${this.data.contact_phone || '-'} 发送短信`
        }).then(() => {
          // TODO: 第二次发送需输入验证码
          Toast.loading({
            duration: 10000,
            forbidClick: true
          })
          resendSms({
            order_no: this.data.order_no,
          }).then(res => {
            Toast.success('发送成功!')
          })
        })
      },

      onDelt() {
        Dialog.confirm({
          message: '确定删除订单？'
        }).then(() => {
          deltOrder({
            order_no: this.data.order_no,
          }).then(res => {
            Toast.success('删除成功!')
            this.$goPage('order/list')
          })
        })
      }
    },

    created() {
      this.getData()
      this.getService()
    },

  }
</script>

<style lang="less" src="@style_m/components/panel.less"></style>
<style lang="less" src="@style_m/mod/order-detail.less"></style><style lang="less" scoped>
  @import "~@style_m/basic/utils/index";
</style>
